import { useMemo } from 'react';
import { TreeSelect } from 'antd';
import { ProFormItem } from '@ant-design/pro-components';
import type { ProFormInstance } from '@ant-design/pro-components';
import useDispatcher from '../../hooks/useDispatcher';
import getProFileData from '../../getProFileData';
import styles from './style.less';
import { uniq } from 'lodash';

type Props = {
  formRef: ProFormInstance | any;
  OptionsTenantList: API.OptionsKeys[];
  tenantFather: string;
};

const TenantRadio: React.FC<Props> = ({ formRef, OptionsTenantList, tenantFather }) => {
  const dispatch = useDispatcher();
  const { formValue, FatherListUniq, OptionsTenantListUniq, QueryChannelIdUniq } = getProFileData();

  // 动态获取optionList
  const enumOptionsData = useMemo(() => {
    const optionsTenantList = [...OptionsTenantList] || [];
    return optionsTenantList;
  }, [OptionsTenantList, tenantFather]);

  const getUseChannelId = (value: string[]) => {
    let useArr: any[] = [];
    OptionsTenantListUniq.forEach((item) => {
      if (value.includes(item.id)) {
        const soloArr = item.useChannelList ? item.useChannelList.split(',') : [];
        useArr = [...useArr, ...soloArr];
      }
    });
    return useArr;
  };

  const getQueryChannelId = (value: string[]) => {
    let queryArr: any[] = QueryChannelIdUniq || [];
    OptionsTenantListUniq.forEach((item) => {
      if (value.includes(item.id)) {
        const soloArr = item.queryChannelList ? item.queryChannelList.split(',') : [];
        queryArr = [...queryArr, ...soloArr];
      }
    });
    return uniq(queryArr);
  };

  // todo--就剩根据obj去给--使用渠道、查询渠道重新赋值;1、缓存接口查到的渠道2、根据当前选的并到一起 并且重新赋值
  const onChangeTree = (value: string[]) => {
    // 赋值--使用渠道\查询渠道
    const curUseChannelId = getUseChannelId(value);
    const curQueryChannelId = getQueryChannelId(value);
    const obj = {
      useChannelId: [...curUseChannelId],
      queryChannelId: [...curQueryChannelId],
    };
    formRef.current?.setFieldsValue({ ...obj });
    dispatch('setFormValue', { ...obj });
  };

  // 操作父级时重新赋值
  const onSelectTree = (value: string, node: any) => {
    // 父级单选
    if (node.parentId === '0' && node.children.length === 0) {
      const obj = {
        tenantList: [node.value],
      };
      formRef.current?.setFieldsValue({ ...obj });
      dispatch('setFormValue', { ...obj });
    }
    // 父级多选
    if (node.parentId === '0' && node.children.length > 0) {
      const sunArr: any = [];
      node.children.forEach((item: any) => {
        sunArr.push(item.value);
      });
      const obj = {
        tenantList: sunArr,
      };
      formRef.current?.setFieldsValue({ ...obj });
      dispatch('setFormValue', { ...obj });
    }
    // 子级单选
    if (node.parentId !== '0') {
      // 1拿到现有的tenantList值，2、收集父级ID-list 并剔除所有父级
      const tenantListBro = formValue.tenantList.filter(
        (item: string) => !FatherListUniq.includes(item),
      );
      tenantListBro.push(node.value);
      const obj = {
        tenantList: tenantListBro,
      };

      formRef.current?.setFieldsValue({ ...obj });
      dispatch('setFormValue', { ...obj });
    }
  };

  return (
    <>
      <div className={styles['wrap-radio-body']}>
        <>
          <ProFormItem
            name="tenantList"
            label="券使用渠道描述"
            labelCol={{ span: 8 }}
            rules={[
              { required: true, message: '不得为空' },
              // {
              //   validator: (_, value) => {
              //     if (value && value.indexOf('-') !== -1)
              //       return Promise.reject(new Error('活动定义不能包含符号-'));
              //     return Promise.resolve();
              //   },
              // },
            ]}
          >
            <TreeSelect
              showSearch
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder=""
              allowClear
              multiple
              treeCheckable={true}
              treeDefaultExpandAll={true}
              onSelect={onSelectTree}
              onChange={onChangeTree}
              treeData={enumOptionsData}
            />
          </ProFormItem>
        </>
      </div>
    </>
  );
};

export default TenantRadio;
